<template>
  <div class="user-management">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>用户信息管理</span>
          <el-button type="primary" @click="handleAdd">新增用户</el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchForm.phone" placeholder="请输入手机号" clearable />
        </el-form-item>
        <el-form-item label="状态" style="width: 180px;">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格区域 -->
      <el-table v-loading="loading" :data="userList" border stripe style="width: 100%">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="150" />
        <el-table-column label="头像" width="100">
          <template #default="scope">
            <el-avatar :size="40" :src="scope.row.avatar" @error="() => true">
              {{ scope.row.username ? scope.row.username.charAt(0).toUpperCase() : 'U' }}
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="realName" label="真实姓名" width="150" />
        <el-table-column label="角色" width="120">
          <template #default="scope">
            <el-tag :type="getRoleTagType(scope.row.role)">
              {{ formatRole(scope.row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="150" />
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column prop="registerTime" label="注册时间" width="200" />
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0"
              @change="handleStatusChange(scope.row.id, scope.row.status)" :disabled="scope.row.role === 'ADMIN'" />
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="300">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)"
              :disabled="scope.row.role === 'ADMIN'">删除</el-button>
            <el-button size="small" type="warning" @click="handleResetPwd(scope.row)">
              重置密码
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增用户' : '编辑用户'" width="600px" destroy-on-close>
      <el-form ref="userFormRef" :model="userForm" :rules="userFormRules" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" :disabled="dialogType === 'edit'" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="userForm.realName" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role">
            <el-option label="管理员" value="ADMIN" />
            <el-option label="设计师" value="DESIGNER" />
            <el-option label="普通用户" value="USER" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status" style="width: 300px;">
          <el-radio-group v-model="userForm.status" >
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="userForm.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="userForm.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog v-model="resetPwdDialogVisible" title="重置密码" width="400px">
      <el-form ref="resetPwdFormRef" :model="resetPwdForm" :rules="resetPwdRules" label-width="100px">
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="resetPwdForm.newPassword" type="password" placeholder="请输入新密码" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="resetPwdForm.confirmPassword" type="password" placeholder="请确认新密码" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetPwdDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitResetPwd">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

export default {
  name: 'UserManagement',
  setup() {
    const { proxy } = getCurrentInstance()

    // 列表状态
    const loading = ref(false)
    const userList = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)

    // 搜索表单
    const searchForm = reactive({
      username: '',
      phone: '',
      status: ''
    })

    // 用户表单
    const userFormRef = ref(null)
    const dialogVisible = ref(false)
    const dialogType = ref('add') // add 或 edit
    const userForm = reactive({
      id: '',
      username: '',
      realName: '',
      phone: '',
      email: '',
      role: 'USER',
      status: 1,
      address: '',
      remark: ''
    })

    // 用户表单验证规则
    const userFormRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      realName: [
        { required: true, message: '请输入真实姓名', trigger: 'blur' }
      ],
      phone: [
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ],
      email: [
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ],
      role: [
        { required: true, message: '请选择角色', trigger: 'change' }
      ]
    }

    // 重置密码表单
    const resetPwdFormRef = ref(null)
    const resetPwdDialogVisible = ref(false)
    const resetPwdForm = reactive({
      userId: '',
      newPassword: '',
      confirmPassword: ''
    })

    // 重置密码表单验证规则
    const resetPwdRules = {
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== resetPwdForm.newPassword) {
              callback(new Error('两次输入的密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ]
    }

    // 获取用户列表
    const getUserList = async () => {
      loading.value = true
      try {
        const params = {
          pageNum: currentPage.value || 1,
          pageSize: pageSize.value || 10,
          ...searchForm
        }
        const res = await request.get('/api/admin/users', { params })
        userList.value = res.data.content || []
        total.value = res.data.totalElements || 0
      } catch (error) {
        console.error('获取用户列表失败:', error)
        ElMessage.error('获取用户列表失败')
      } finally {
        loading.value = false
      }
    }

    // 搜索
    const handleSearch = () => {
      currentPage.value = 1
      getUserList()
    }

    // 重置搜索
    const resetSearch = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''
      })
      currentPage.value = 1
      getUserList()
    }

    // 改变每页条数
    const handleSizeChange = (val) => {
      pageSize.value = val
      getUserList()
    }

    // 改变页码
    const handleCurrentChange = (val) => {
      currentPage.value = val
      getUserList()
    }

    // 新增用户
    const handleAdd = () => {
      dialogType.value = 'add'
      Object.keys(userForm).forEach(key => {
        userForm[key] = key === 'role' ? 'USER' : key === 'status' ? 1 : ''
      })
      dialogVisible.value = true
    }

    // 编辑用户
    const handleEdit = (row) => {
      dialogType.value = 'edit'
      Object.keys(userForm).forEach(key => {
        userForm[key] = row[key]
      })
      dialogVisible.value = true
    }

    // 提交表单
    const submitForm = async () => {
      if (!userFormRef.value) return

      await userFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            const url = dialogType.value === 'add' ? '/api/admin/users' : `/api/admin/users/${userForm.id}`
            const method = dialogType.value === 'add' ? 'post' : 'put'
            await request[method](url, userForm)
            ElMessage.success(dialogType.value === 'add' ? '添加成功' : '修改成功')
            dialogVisible.value = false
            getUserList()
          } catch (error) {
            console.error(dialogType.value === 'add' ? '添加失败:' : '修改失败:', error)
          }
        }
      })
    }

    // 删除用户
    const handleDelete = (row) => {
      ElMessageBox.confirm('确认删除该用户吗？此操作不可恢复！', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await request.delete(`/api/admin/users/${row.id}`)
          ElMessage.success('删除成功')
          getUserList()
        } catch (error) {
          console.error('删除失败:', error)
        }
      }).catch(() => { })
    }

    // 修改用户状态
    const handleStatusChange = async (id, status) => {
      try {
        await request.put(`/api/admin/users/${id}/status`, { status })
        ElMessage.success('状态修改成功')
      } catch (error) {
        console.error('状态修改失败:', error)
        getUserList() // 刷新列表，恢复原状态
      }
    }

    // 重置密码
    const handleResetPwd = (row) => {
      resetPwdForm.userId = row.id
      resetPwdForm.newPassword = ''
      resetPwdForm.confirmPassword = ''
      resetPwdDialogVisible.value = true
    }

    // 提交重置密码
    const submitResetPwd = async () => {
      if (!resetPwdFormRef.value) return

      await resetPwdFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            await request.put(`/api/admin/users/${resetPwdForm.userId}/password/reset`, {
              newPassword: resetPwdForm.newPassword
            })
            ElMessage.success('密码重置成功')
            resetPwdDialogVisible.value = false
          } catch (error) {
            console.error('密码重置失败:', error)
          }
        }
      })
    }

    // 格式化角色
    const formatRole = (role) => {
      const roleMap = {
        'ADMIN': '管理员',
        'DESIGNER': '设计师',
        'USER': '普通用户'
      }
      return roleMap[role] || role
    }

    // 获取角色标签类型
    const getRoleTagType = (role) => {
      const typeMap = {
        'ADMIN': 'danger',
        'DESIGNER': 'warning',
        'USER': ''
      }
      return typeMap[role] || ''
    }

    // 初始化
    onMounted(() => {
      getUserList()
    })

    return {
      loading,
      userList,
      currentPage,
      pageSize,
      total,
      searchForm,
      dialogVisible,
      dialogType,
      userForm,
      userFormRef,
      userFormRules,
      resetPwdDialogVisible,
      resetPwdForm,
      resetPwdFormRef,
      resetPwdRules,
      handleSearch,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      handleAdd,
      handleEdit,
      submitForm,
      handleDelete,
      handleStatusChange,
      handleResetPwd,
      submitResetPwd,
      formatRole,
      getRoleTagType
    }
  }
}
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 16px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  padding-top: 20px;
  text-align: right;
}
</style> 